import { watch } from 'vue'
import store from '../store'
import { THEME_DARK, THEME_LIGHT, THEME_SYSTEM } from '@/constants'

/**
 * 监听系统主题变更
 */
let matchMedia
const watchSystemThemeChange = () => {
  // 仅需一次初始化
  if (matchMedia) return
  matchMedia = window.matchMedia('(prefers-color-scheme: dark)')
  // 监听系统主题变化
  matchMedia.onchange = () => {
    changeTheme(THEME_SYSTEM)
  }
}

// 切换主题
const changeTheme = (themeType) => {
  let themeClassName = ''
  switch (themeType) {
    case THEME_LIGHT:
      themeClassName = 'light'
      break
    case THEME_DARK:
      themeClassName = 'dark'
      break
    case THEME_SYSTEM:
      // 调用方法监听系统主题变化
      watchSystemThemeChange()
      themeClassName = matchMedia ? 'drak' : 'light'
      break
  }
  // 修改htmlClass
  document.querySelector('html').className = themeClassName
}

/**
 * 初始化主题
 */
export default () => {
  // 1. 当主题发生改变时或者当进入系统时 可以对html根标签进行class配置
  watch(
    () => store.getters.themeType,
    (val) => {
      changeTheme(val)
    },
    { immediate: true }
  )
}
